package com.timmy.bledemo;

import android.app.ProgressDialog;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    @BindView(R.id.main_lv)
    ListView mListView;
    private BleUtils mBleUtils;
    private ProgressDialog mDialog;
    private MyAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        mDialog = new ProgressDialog(this);
        mDialog.setCanceledOnTouchOutside(false);

        mAdapter = new MyAdapter(this);
        mListView.setAdapter(mAdapter);

        mListView.setOnItemClickListener(this);

        mBleUtils = BleUtils.getInstance().init(this);
    }

    @OnClick(R.id.main_btn)
    public void onViewClicked() {
        mDialog.show();
        mBleUtils.scanDevice(new BleScanCallback() {
            @Override
            public void onBleScan(List<DeviceInfo> list) {
                mDialog.dismiss();
                mAdapter.setData(list);
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        mDialog.show();
        final BluetoothDevice item = mAdapter.getItem(position);

        mBleUtils.connectDevice(item, new BleConnectCallback() {
            @Override
            public void onConnectSuccess() {
                mDialog.dismiss();

                if (item.getName().contains("H001")) {
                    mBleUtils.setIsFactory(false);
                } else {
                    mBleUtils.setIsFactory(true);
                }

                mBleUtils.setMac(item.getAddress());
                Intent intent = new Intent(MainActivity.this, InfoActivity.class);
                startActivity(intent);
                finish();
            }

            @Override
            public void onConnectFailure() {
                mDialog.dismiss();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }
}
